package _06_动态规划;

import java.util.Arrays;

/**
 * https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/
 * @Author: haogege
 * @Date: 2021/9/13
 */
public class _714_买卖股票的最佳时机含手续费 {

    public static void main(String[] args) {


        int[] ins = {4,5,5,2,4,3,5,5,2,3};

        _714_买卖股票的最佳时机含手续费 v = new _714_买卖股票的最佳时机含手续费();

        System.out.println(v.maxProfit(ins, 3));
    }

    // 动态规划
    public int maxProfit(int[] prices, int fee) {
        int len = prices.length;
        int[][] dp = new int[len][2];
        dp[0][1] = -prices[0];

        for (int i = 1; i < len; i++) {
            dp[i][0] = Math.max(dp[i][0], dp[i][1] + prices[i] - fee);
            dp[i][1] = Math.max(dp[i][1], dp[i][1] - prices[i]);
        }
        return dp[len - 1][0];
    }

    // 贪心算法
    public int maxProfit3(int[] prices, int fee) {
        int n = prices.length;
        int buy = prices[0] + fee;
        int profit = 0;
        for (int i = 1; i < n; ++i) {
            if (prices[i] + fee < buy) {
                buy = prices[i] + fee;
            } else if (prices[i] > buy) {
                profit += prices[i] - buy;
                buy = prices[i];
            }
        }
        return profit;
    }

    // 动态规划
    public int maxProfit2(int[] prices, int fee) {
        int n = prices.length;

        int[][] dp = new int[n][2];

        dp[0][1] = -prices[0];

        for (int i = 1; i < prices.length; i++) {
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i] - fee);
            dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
        }
        return dp[n - 1][0];
    }

}
